import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
//import java.sql.SQLException;
import java.util.ArrayList;

import ApacheClient.ApacheClient;
import Parser.ParseTree;
import Parser.Token;

//import com.mysql.jdbc.ResultSet;
//import com.mysql.jdbc.Statement;

/**
 *
 * @author Chris
 */
public class SwitchBoard {
    private ApacheClient client = new ApacheClient();
    private int queryDelay = 0;
    private int pageDelay = 0;
    private int pDelayRange = 0;
    private int qDelayRange = 0;
    private ArrayList <String> nameList = new ArrayList<String>();
    private ArrayList <String> streetAddressList = new ArrayList<String>();
    private ArrayList <String> zipcodeList = new ArrayList<String>();
    private ArrayList <String> cityList = new ArrayList<String>();
    private ArrayList <String> stateList = new ArrayList<String>();
    private ArrayList <String> phoneList = new ArrayList<String>(); 
    //private ArrayList <String> ageList = new ArrayList<String>();  
    private int g =0;

    Connection conn = null;
    String userName = "root";
    String password = "admin";
    String url = "jdbc:mysql://localhost/aparna";
    
    public Connection getConn()
    {
    	
    	try
    	{
    	Class.forName ("com.mysql.jdbc.Driver").newInstance ();
        conn = DriverManager.getConnection (url, userName, password);
        System.out.println ("Database connection established");
    	}
   	
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	
    	return conn;
    	  	
    	}
    	
    
    	
    
    public SwitchBoard() {

    }

    public SwitchBoard(int queryDelay, int pageDelay) {
        this.queryDelay = queryDelay;
        this.pageDelay = pageDelay;
    }

    public SwitchBoard(int queryDelay, int pageDelay, int qDR, int pDR) {
        this.queryDelay = queryDelay;
        this.pageDelay = pageDelay;
        qDelayRange = qDR;
        pDelayRange = pDR;
    }

    protected void pageDelay() throws Exception {
        // A pointless delay
        Thread.sleep(pageDelay + (int) (Math.random() * pDelayRange));
    }

    protected void queryDelay() throws Exception {
        // A pointless delay
        Thread.sleep(queryDelay + (int) (Math.random() * qDelayRange));
    }

    // Replace unacceptable entries with valid ones
    protected String firstNameQuery(String query) {
        String result[];
        result = query.split(" ");
        return result[0];
    }

    
    protected String lastNameQuery(String query) {
        String result[];
        result = query.split(" ");
        return result[1];
    }
    
    
    public InputStream submitQuery(String query, int page) throws Exception {
        System.out.println("Query is" + query);
        
        //http://people.switchboard.com/results.php?ReportType=34&qf=Adam&qi=0&qk=10&qn=Myers&page=2&sz=10
        //http://people.switchboard.com/results.php?ReportType=34&qf=Adam&qn=Myers&qi=0&qk=10
        //http://people.switchboard.com/results.php?ReportType=34&qf=Adam&qn=Myers&qi=10&qk=10
        //http://people.switchboard.com/results.php?ReportType=34&qf=Adam&qn=Myers&qi=20&qk=10
        
        String prefix = "http://people.switchboard.com/results.php?ReportType=34&qf=" + firstNameQuery(query) + "&qn=" + lastNameQuery(query) + "&qi=";
        String suffix = "&qk=10&qs=TX";
        String urltext;
//        String GetUrl= this.getURL();
        //System.out.println("Url is " + GetUrl);
        //query = firstNameQuery(query) + lastNameQuery(query);

      /*  if (page <= 1)
            urltext = prefix + suffix;
        else*/
            urltext = prefix + (page-1)*10 + suffix;
   System.out.println(urltext);
        return client.getPage(urltext);
    }

    public ArrayList<SearchResult> getResults(String query, int page) throws Exception {
        ArrayList<SearchResult> result = new ArrayList<SearchResult>();
        InputStream content = submitQuery(query, page);
        BufferedReader read = new BufferedReader(new InputStreamReader(content));
        ParseTree tree = new ParseTree(read);
        Token[] tokens = tree.getTokens();
        int pos;
        int pos2;
        int pos1;
        int pos3;
        int pos4;
    
        String name;
      //  String location;
        //String age;
        String att;
        //String summary;
        int id;
        
        StringBuffer restAddress = new StringBuffer(200);
		StringBuffer addressWithoutSpace = new StringBuffer(200);
		String street_address = new String();
		String city = new String();
		String state = new String();
        String zipcode = new String();
        String phone = new String();
        String region = new String();
        conn = getConn();
        
        id = 1825 + page*10;
        
        String insert_query = "INSERT INTO person(idperson, name, url,street_address, phone,city,state,zipcode) values (?,?,?,?,?,?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(insert_query);   

    	String commit_query = "commit";
       PreparedStatement commitStmt = conn.prepareStatement(commit_query); 

        // Get the <a ...> tags for Name
        pos = tree.findNextTag(0, Token.A);
        System.out.println(pos);
        
               
            while (pos >= 0) {
        	att = tokens[pos].valueOfAtt("class");

        	//IF loop for Name
        	if (att != null && att.equalsIgnoreCase("resultName")) {
              System.out.println("Found column DON");
              pos2 = tree.findNextClose(pos);
        	       System.out.println("Name is " + tree.getAllText(pos, pos2).toString());
                name = tree.getAllText(pos, pos2).toString();
                nameList.add(name);
         
            }
              pos = tree.findNextTag(pos + 1, Token.A);
        }
        // Get the  tags for address
        pos1 = tree.findNextTag(0, Token.DIV);
        System.out.println(pos1);
       while (pos1 >= 0){
           att = tokens[pos1].valueOfAtt("class");
        if (att != null && att.equalsIgnoreCase("listingInfo")) {
              System.out.println("Found column Snoopy");
              pos2 = tree.findNextTag(pos1, Token.BR);
              pos3 = tree.findNextClose(pos2);
        	       System.out.println("Street Address is " + tree.getAllText(pos1, pos2).toString());
        	       System.out.println("Rest is " + tree.getAllText(pos2, pos3).toString());
        	       street_address = tree.getAllText(pos1, pos2).toString();
        	       restAddress = tree.getAllText(pos2, pos3);
                
                addressWithoutSpace = new StringBuffer(150);
                city = new String();
        		state = new String();
                
        		for(int k =0;k<restAddress.length();k++)
        		{
        			//System.out.println("Char at " + k + allLocations.charAt(k));   			
        			//g=k;
        			if(restAddress.charAt(k) != ' ')
        			{
        				addressWithoutSpace.append(restAddress.charAt(k));

        			}
        		}
        			System.out.println("Without space address is" + addressWithoutSpace);
        			String delimsCity = "[,]+";
        			String[] splittedAddress =  addressWithoutSpace.toString().split(delimsCity);
        			 System.out.println("Splitted address is" + splittedAddress[0]);
        			if(splittedAddress.length > 1)
        			{
        			city = splittedAddress[0];
        			region = splittedAddress[1];
        			}
        			
        			state = region.substring(0, 2);
        			zipcode = region.substring(2, region.length());
        			
        			streetAddressList.add(street_address);
        			cityList.add(city);
        			stateList.add(state);
        			zipcodeList.add(zipcode);
        		}
        		
        		addressWithoutSpace.delete(0, addressWithoutSpace.length());
            
        pos1 = tree.findNextTag(pos1 + 1, Token.DIV);
       }
        
       // Get the  tags for Phone
        pos4 = tree.findNextTag(0, Token.DIV);
        System.out.println(pos4);
       while (pos4 >= 0){
           att = tokens[pos4].valueOfAtt("class");
        if (att != null && att.equalsIgnoreCase("phone")) {
              System.out.println("Found column Tring Tring");
              pos2 = tree.findNextClose(pos4);
        	       System.out.println("Location is " + tree.getAllText(pos4, pos2).toString());
                phone = tree.getAllText(pos4, pos2).toString();
         phoneList.add(phone);
            }
        pos4 = tree.findNextTag(pos4 + 1, Token.DIV);
       }
       
       
    	while(g<nameList.size())
       	{
       		pstmt.setInt(1, id);  
           	   pstmt.setString(2, nameList.get(g));
           	   pstmt.setString(3,"people.switchboard.com");
           	pstmt.setString(4,streetAddressList.get(g));
        	 pstmt.setString(5,phoneList.get(g)); 	   
     	 pstmt.setString(6,cityList.get(g));
     	 pstmt.setString(7,stateList.get(g));
     	 pstmt.setString(8,zipcodeList.get(g));
     	pstmt.execute();
     	 commitStmt.execute();
     	System.out.println("Added Name" + nameList.get(g));
       	System.out.println("Added ID " + id);
     	 
     	 g++;
       	
      	 id++;
       	
       	}
       
         /* 	if (att != null && att.equalsIgnoreCase("column ix2")) {
                //url = tokens[pos].valueOfAtt("a");
                 
          		
              //  String location = String(tree.getAllTextInsideToken(pos));
               // tokens[pos].getAllTextInsideToken(pos);
                pos2 = tree.findNextTag(pos + 1, Token.DIV);
                pos3 = tree.findNextTag(pos2 + 1, Token.DIV);
              System.out.println("Name is " + tree.getAllText(pos, pos3));
                summary = tree.getAllText(pos2, pos3).toString();
                
                if (!name.startsWith("Name/Aliases")) {
              	  /* pstmt.setInt(1, id);  
              	   pstmt.setString(2, name); 
              	   
              	   
              	   result.add(new SearchResult(name, summary));
              	   
              	   
                  }
                
                
               
            }*/
        	
        	
        	
        	/*if (att != null && att.equalsIgnoreCase("column ix1")) {
                //url = tokens[pos].valueOfAtt("a");
                      
                //String age = tree.getAllTextInsideToken(pos));
               // tokens[pos].getAllTextInsideToken(pos);
                pos2 = tree.findNextTag(pos + 1, Token.DIV);
                pos3 = tree.findNextTag(pos2 + 1, Token.DIV);
                summary = tree.getAllText(pos2, pos3).toString();
               
            }*/
      

        read.close();

        return result;
    }

    public ArrayList<SearchResult> getResults(String query, int startPage, int endPage) throws Exception {
        ArrayList<SearchResult> result = new ArrayList<SearchResult>();

        for (int c = startPage; c <= endPage; c++) {
            result.addAll(getResults(query, c));
        }

        return result;
    }

    public ArrayList<SearchResult> getResultsWithDelay(String query, int startPage, int endPage) throws Exception {
        ArrayList<SearchResult> result = new ArrayList<SearchResult>();

        for (int c = startPage; c <= endPage; c++) {
            result.addAll(getResults(query, c));
            pageDelay();
        }

        return result;
    }
    
    
  /* public int getMaxID()
    {
    	conn = getConn();
    	int maxid = 0;
    	try
    	{
    	Statement stmt = conn
		String query = "select max(idperson) from person";
		   //executing query and get the maximum id
		System.out.println(query);
		   ResultSet rs1 = stmt.executeQuery(query);
		   rs1.next();
		   System.out.println("Rs1" + rs1.next());
		   System.out.println(rs1.getInt("idperson"));
		   maxid = rs1.getInt("idperson");
    	}
    	catch(SQLException se)
    	{
    		se.printStackTrace();
    	}
		   
		   return maxid;
    }*/
    
    //getmaxID ends
/*    public String getURL () throws Exception{
        String result="" ;
      InputStream content = submitQuery("John Huntsman ", 1);
      BufferedReader read = new BufferedReader(new InputStreamReader(content));
        ParseTree tree = new ParseTree(read);
        Token[] tokens = tree.getTokens();
        int pos;
        int pos2;
        int pos3;
        
         String name;
        String location;
        String age;
        String att;
        String summary;
        int id;
        pos = tree.findNextTag(0, Token.A);
        while (pos >= 0) {
         att = tokens[pos].valueOfAtt("class");
            if (att != null && att.equalsIgnoreCase("search_results_header")) {
                System.out.println(tokens[pos].valueOfAtt("href"));
                url = tokens[pos].valueOfAtt("href");
                pos2 = tree.findNextTag(pos + 1, Token.DIV);
                pos3 = tree.findNextTag(pos2 + 1, Token.SPAN);
                summary = tree.getAllText(pos2, pos3).toString();
                //summary = tree.getAllTextInsideToken(pos2).toString();
             // if (!url.startsWith("http://www.youtube.com")) {
               //     result.add(new SearchResult(url, summary));
               // }
               // System.out.println(url);
            }
            pos = tree.findNextTag(pos + 1, Token.A);
          
        }

        read.close();

        return result;
    }*/

    
}


